<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\Subscribe as SubscribeModel;
use app\shouyin\model\Operation as OperationModel;
use app\system\model\systemUser as systemUserModel;
use think\Db;
use app\user\model\User as UserModel;
use app\shop\model\Room as RoomModel;
use app\product\model\Project as ProjectModel;
use app\product\model\Unit as UnitModel;
use app\product\model\Product as ProductModel;
use app\product\model\ProjectProduct as ProjectProductModel;
use app\warehouse\model\Warehouse as WarehouseModel;
use app\warehouse\model\Stock as StockModel;

use think\facade\Cache;
use app\finance\model\Account as AccountModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\SubscribeProject as SubscribeProjectModel;
use app\finance\model\SystemBalanceLog as SystemBalanceLogModel;
use app\shouyin\model\UserCardDetailLog as UserCardDetailLogModel;
/**
 *  预约单
 */
class Subscribe extends Admin
{
    protected $hisiModel = 'Subscribe';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        $this->assign('users', UserModel::field('id,nick')->all());
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];

            $where['shop_id'] = session('shop_id');

            // 房间
            // $rooms = RoomModel::getSelect(RoomModel::where($where)->all());
            // $this->assign('rooms', $rooms);
            $this->assign('rooms', RoomModel::where($where)->all());
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            $warehouse_admins = [];
            $cashiers = [];
            $finances = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }else if($value['type'] == '库管'){
                    $warehouse_admins[] = $value;
                }else if($value['type'] == '前台'){
                    $cashiers[] = $value;
                }else if($value['type'] == '财务'){
                    $finances[] = $value;
                }
            }

            // $this->assign('finances', systemUserModel::getSelect($finances));
            $this->assign('finances', $finances);
            // $this->assign('cashiers', systemUserModel::getSelect($cashiers));
            $this->assign('cashiers', $cashiers);
            // $this->assign('warehouse_admins', systemUserModel::getSelect($warehouse_admins));
            $this->assign('warehouse_admins', $warehouse_admins);
            // $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('advisers', $advisers);
            $this->assign('technicians', $technician);
            $projects = ProjectModel::field('*, id as project_id, name as project_name')->all();
            $this->assign('projects', $projects);

            $this->assign('products', ProductModel::getSelect(ProductModel::all()));
            $warehouse= WarehouseModel::where('shop_id',session('shop_id'))->field('id,name,type')->all();
            $this->assign('warehouses',$warehouse);
            $products = ProductModel::where('status',1)->field('id,name,name as product_name,specs,unit_id, unit_id as unit_text,  decomposition_id,decomposition_id as decomposition_text,price2')->select();
            $this->assign('products',$products);
        }
        // $account = AccountModel::getSelect(AccountModel::all());
        $this->assign('accounts',AccountModel::all());
        // halt($account);

    }
    public function index()
    {
        
        $state     = $this->request->param('state');
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id      = $this->request->param('user_id/d', '');
            $start      = $this->request->param('start', '2000-01-01');
            $end      = $this->request->param('end','');
            
            if(session('admin_type') == '顾问'){
                $where['status'] = 0;
            }else if(session('admin_type') == '库管'){
                $where['status'] = 1;
            }else if(session('admin_type') == '前台'){
                $where['status'] = [2,5];
            }else if(session('admin_type') == '财务'){
                $where['status'] = [3,4];
            }else if(session('admin_type') == '管理员'){

            }
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                // $end = date('Y-m-d',time());
                $end = date('Y-m-d',strtotime("+1 day"));
            }
            $sysUser = systemUserModel::column('id,nick');
            $where['shop_id'] = session('shop_id');
            // halt($where);
            if($state){
                $data['data'] = SubscribeModel::with(['hasShop','hasRoom','hasUser'])
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                                ->where($where)
                                ->where('status',5)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
                $data['count'] = SubscribeModel::where($where)->where('status',5)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');
            }else{
                // halt(1);
                $data['data'] = SubscribeModel::with(['hasShop','hasRoom','hasUser'])
                ->where('createtime','between',[strtotime($start),strtotime($end)])
                                ->where($where)
                                ->where('status','<>',5)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
                $data['count'] = SubscribeModel::where($where)->where('status','<>',5)->where('createtime','between',[strtotime($start),strtotime($end)])->count('id');


            }
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['adviser'] = $sysUser[$data['data'][$key]['adviser_id']];
                $data['data'][$key]['technician'] = Db::name('system_user')->where('id','in',$data['data'][$key]['technician_ids'])->column('nick');
                $data['data'][$key]['projects'] = Db::name('project')->where('id','in',$data['data'][$key]['project_ids'])->column('name');
                $data['data'][$key]['cashier'] = Db::name('system_user')->where('id','in',$data['data'][$key]['cashier_id'])->column('nick');
                $data['data'][$key]['warehouse_admin'] = Db::name('system_user')->where('id','in',$data['data'][$key]['warehouse_admin'])->column('nick');
                $data['data'][$key]['finance'] = Db::name('system_user')->where('id','in',$data['data'][$key]['finance_id'])->column('nick');
                // $data['data'][$key]['cashier'] = Db::name('system_user')->where('id','in',$data['data'][$key]['cashier_id'])->column('nick');
            }


            $data['code'] = 0;
            return json($data);

        }
        if($state){
            $this->assign('state',$state);
            return $this->fetch();
        }else{
            return $this->fetch('operation');
        }

    }

    public function add()
    {
        if($this->request->isPost()){
            $postData = $this->request->post();

                if($postData['user_id'] == ''){
                    return $this->axiosMsg("预约会员不能为空", false);
                }
                if($postData['adviser_id'] == ''){
                    return $this->axiosMsg("预约顾问不能为空", false);
                }
                if($postData['project_ids'] == ''){
                    return $this->axiosMsg("预约项目不能为空", false);
                }
                $postData['appointment_time'] = date('Y-m-d H:i:s',$postData['appointment']);
                $postData['time1'] = time();
                $postData['sn'] = create_order_sn();

                $postData['shop_id'] = session('shop_id');
                $SubscribeModel = new SubscribeModel;
                if(!$SubscribeModel->save($postData)){
                    return $this->axiosMsg('提交失败，请重试',false);
                }

            return $this->axiosMsg('提交成功',true);
        }
        return $this->fetch();
    }


    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {
                if($postData['user_id'] == ''){
                    return $this->axiosMsg("预约会员不能为空", false);
                }
                if($postData['adviser_id'] == ''){
                    return $this->axiosMsg("预约顾问不能为空", false);
                }
                if($postData['project_ids'] == ''){
                    return $this->axiosMsg("预约项目不能为空", false);
                }
                $postData['appointment_time'] = date('Y-m-d H:i:s',$postData['appointment']);
                if ($model->save($postData, $where) === false) {
                    return $this->axiosMsg($model->getError(),false);
                }

                return $this->axiosMsg('保存成功', true);
            }

            $formData = $model->where($where)->find();

        }

        if (!$formData) {
            return $this->axiosMsg('数据不存在或没有权限',fslse);
        }
        $formData['appointment'] = strtotime($formData['appointment_time'])*1000;
        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }
    /**
     * 开单，谁都可以操作， 不做限制
     */
    public function kaidan()
    {

        $id = $this->request->param('id/a');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        $subscribeInfo = SubscribeModel::get($id);
        if($subscribeInfo->status == 2){
            return $this->error('预约单已经开单！');
        }else if($subscribeInfo->status == 3){
            return $this->error('预约单无效！');
        }
         Db::startTrans();
        try {
        // 更新预约单状态
            $subscribeInfo->status = 0;
            $subscribeInfo->time2 = time();

            $projects = Db::name('project')->where('id','in',$subscribeInfo->project_ids)->select();
            // halt($projects);
            foreach ($projects as $key => $value) {
                $pros[] = [
                    'project_id' => $value['id'],
                    'project_name' => $value['name'],
                    'is_give' => 1,
                    'price' => $value['price'],
                    'technician_ids' => $subscribeInfo->technician_ids,
                    'adviser_id' => $subscribeInfo->adviser_id,
                    'bak' => '',
                    'type' => 1,  //项目分类:1=实操项目,2=特殊项目
                    'num' => 1,
                    'settlement' => 1,  // 结算方式：1=现金消费，2=储值卡，3=赠送，4=疗程卡
                    'shougong' => 0
                ];
            }
            $subscribeInfo->project_data = json_encode($pros,true);
            $res = $subscribeInfo->save();
            // Db::name('subscribe_project')->insertAll($pros);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            // return $this->axiosMsg($e->getMessage(),false);
             return $this->error('开单失败:'.$e->getMessage());
        }

        return $this->success('开单成功');
    }
    /**
     * 顾问开单
     * @author qinty.net <282512951@qq.com>
     * @return mixed
     */
    public function gwkd()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);
  
            if ($this->request->isPost()) {
                if($postData['adviser_id'] == ''){
                    return $this->axiosMsg('审核顾问不能能为空',false);
                }
                $postData['project_data'] = json_encode($postData['project_data']);
                $postData['status'] = 1;
                $postData['time3'] = time();
                // echo $model->save($postData, $where)
                if ($model->save($postData, $where) === false) {
                    return $this->axiosMsg($model->getError(),false);
                }
                return $this->axiosMsg('保存成功',true);
            }

            $formData = $model->where($where)->find();

        }
        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);
        // $project_data = Db::name('subscribe_project')->where('sub_id',$formData['id'])->select();
        $this->assign('project_data', json_decode($formData->project_data));
        // halt($project_data);
        $template = $this->request->param('template', 'form');

        return $this->fetch('gwkd');
    }

    /**
     * 库管开单
     */
    public function kgkd()
    {

        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();

        }

        $where = [];

        $model = $this->model();

        $pk = $model->getPk();
        $id = $this->request->param($pk);
        $where[]= [$pk, '=', $id];
        $where  = $this->getRightWhere($where);
        if ($this->request->isPost()) {
            if(!isset($postData['warehouse_admin']) || empty($postData['warehouse_admin'])){
                return $this->axiosMsg('库管为必填项',false);
            }

            $product_data = $postData['product_data'];
            foreach($product_data as $k => $v){
                if(!isset($v['warehouse_id']) || empty($v['warehouse_id'])){
                    return $this->axiosMsg('仓库为必填项',false);
                }
            }
            $postData['product_data'] = 
            $postData['product_data'] = json_encode($postData['product_data']);
            if($model->save($postData, $where) === false){
                return $this->axiosMsg($e->getError(),false);
            }

            return $this->axiosMsg('提交成功', true);
        }

        $formData = $model->where($where)->find();
        $project_data = json_decode($formData['project_data'],true);
        $product_data = [];
        foreach ($project_data as $key => $value) {
            // $product_data[] = Db::name('project_product')->where('project_id',$value['project_id'])->select();
            $project_data[$key]['product'] = ProJectProductModel::alias('pp')
            ->join('product p','p.id=pp.product_id')
            ->field('pp.*,p.unit_id,p.decomposition_id,p.name')
            ->where('project_id',$value['project_id'])
            ->select();
        }
        $unit = Db::name('unit')->column('id,name');
        foreach ($project_data as $key => $value) {
            foreach ($project_data[$key]['product'] as $k => $v) {
                $project_data[$key]['product'][$k]['unit_text'] = $unit[$v['unit_id']];
                $project_data[$key]['product'][$k]['decomposition_text'] = $unit[$v['decomposition_id']];
            }
        }
        // halt($project_data);
        $this->assign('project_data', $project_data);
        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);
        $warehouse= WarehouseModel::where('shop_id',session('shop_id'))->where('type',1)->field('id,name,type')->all();
        $this->assign('warehouses',$warehouse);
        $template = $this->request->param('template', 'form');

        return $this->fetch();
    }



    /**
     * 收银结算
     */
    public function sykd()
    {
        $id = $this->request->param('id');
        $formData = SubscribeModel::get($id);
        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }
        $this->assign('formData', $formData);
        $this->assign('project_data', json_decode($formData->project_data,true));

        // 用户余额
        $userModel = new UserModel;
        // 检查用户余额是否足够
        $userBalance = $userModel->getUserBalance($formData['user_id'],1);
        $userBalanceZeng = $userModel->getUserBalance($formData['user_id'],2);

        $this->assign('userBalance',$userBalance);
        $this->assign('userBalanceZeng',$userBalanceZeng);

        if($this->request->isPost()){
            $postData = $this->request->post();
            if($postData['status'] == 1){
                Db::name('subscribe')->where('id',$id)->update(['status'=>1]);
                return $this->axiosMsg('回退成功！', true);
            }

            if(!isset($postData['account_id']) || empty($postData['account_id'])){
                return $this->axiosMsg('收款账户为必填项！', false);
            }
            if(!isset($postData['cashier_id']) || empty($postData['cashier_id'])){
                return $this->axiosMsg('收银为必填项！', false);
            }
            // 项目结算
            $projects = $postData['projects'];
            $buyProducts = $postData['products'];

            $price1 = 0; //项目现金支付
            $price2 = 0; //项目会员卡支付
            $price5 = 0; //项目会员卡支付
            $card_ject = [];

            foreach ($projects as $key => $value) {
                if($value['settlement'] == 1){          // 现金支付
                    $price1 += $value['price'];
                } else if ($value['settlement'] == 2) {  // 会员卡
                    $price2 += $value['price'];
                } else if ($value['settlement'] == 3) {  // 赠送
                    $price3 = 0;
                } else if ($value['settlement'] == 4) {  // 疗程卡
                    $card_ject[$value['card_pid']][] = $value['card_num'];
                    if(!isset($value['card_pid']) || $value['project_id'] != $value['card_pid']){
                        return $this->axiosMsg('项目和疗程卡不对等！', false);
                    }
                  
                } else if ($value['settlement'] == 10000) {  // 会员卡赠送余额
                    $price5 += $value['price'];
                }
            }
            
            // 判断项目疗程卡是否够用
            if(!empty($card_ject)){
                foreach ($card_ject as $key => $value) {
                     $project_num = Db::name('user_card_log')
                                    ->where('user_id',$formData['user_id'])
                                    ->where('pid',$key)->where('use',1)
                                    ->where('type',1)->count('id');
                     if(array_sum($card_ject[$key]) > $project_num){
                         return $this->axiosMsg("疗程卡不足",false);
                     }
                 }
            }
            // die;
            // 新购产品结算..
            $pricePro1 = 0; //产品支付
            $pricePro2 = 0; //产品会员卡支付
            $pricePro5 = 0; //产品会员卡赠送余额
            $card_duct = []; // 产品卡
            foreach ($buyProducts as $key => $value) {
                if($value['settlement'] == 1){          // 现金支付
                    $pricePro1 += $value['price2'];
                } else if ($value['settlement'] == 2) {  // 会员卡
                    $pricePro2 += $value['price2'];
                } else if ($value['settlement'] == 3) {  // 赠送
                    $pricePro3 = 0;
                } else if ($value['settlement'] == 4) {  // 疗程卡
                    // 暂未修改，准备去掉产品卡  没有什么作用
                    $card_duct[$value['product_id']][] = $value['num'];   
                } else if ($value['settlement'] == 10000) {  // 会员卡赠送余额
                    $pricePro5 += $value['price2'];
                }
            }
            // 判断项目产品卡是否够用
            if(!empty($card_duct)){
                foreach ($card_duct as $key => $value) {
                     $product_num = Db::name('user_card_log')->where('user_id',$formData['user_id'])->where('pid',$key)->where('use',1)->where('type',2)->count('id');
                     if(array_sum($card_duct[$key]) > $product_num  || $product_num == 0){
                         return $this->axiosMsg("产品卡不足",false);
                     }
                 }
            }
            // 判断用户会员卡是否够用
            $balancePay = $price2 + $pricePro2;
            if($userBalance < $balancePay){
                return $this->axiosMsg("会员卡余额不足",false);
            }
            // 会员卡赠送余额
            $balancePay5 = $price5 + $pricePro5;
            if($userBalanceZeng < $balancePay5){
                return $this->axiosMsg("会员卡赠送余额不足",false);
            }
            // 现金支付金额
            $moneyPay = $price1 + $pricePro1;

            $postData['project_data'] = json_encode($postData['projects']);
            $postData['buy_product'] = json_encode($postData['products']);
            $postData['recharge'] = json_encode($postData['recharge']);
            $postData['card_data'] = json_encode($postData['cardData']);
            $postData['time3'] = time();
            unset($postData['products']);
            unset($postData['projects']);
            unset($postData['card_price']);
            unset($postData['cardData']);

            $product_data = json_decode($formData->product_data,true);
            // halt($product_data);
            // $warehouse_stock = Db::name('warehouse')->where('shop_id',$formData['shop_id'])->column('type,id');
            // 余额和疗程卡检测完成   接下来减库存，结算金额
            Db::startTrans();
            try {
                // 修改操作单
                Db::name('subscribe')->where('id',$id)->update($postData);
                $StockModel = new StockModel;
                // 项目生成库存
                if($product_data){
                    foreach ($product_data as $key => $value) {
                        $begin_num = $StockModel->getBeginNum($value['warehouse_id'],$value['product_id']);
                        $product_price = $StockModel->getProductPrice($value['warehouse_id'],$value['product_id']); // 成本价
                        if($product_price == 0){
                            $product_info = ProductModel::get($value['product_id']);
                            $product_price = $product_info->price1;
                        }
                        $stockJectArr[$key]['sn'] = $formData['sn'];
                        $stockJectArr[$key]['product_id'] = $value['product_id'];
                        $stockJectArr[$key]['product_num'] = $value['product_num'];
                        $stockJectArr[$key]['product_name'] = $value['product_name'];
                        $stockJectArr[$key]['shop_id'] = $formData['shop_id'];
                        $stockJectArr[$key]['type'] = '出库';
                        $stockJectArr[$key]['bak'] = '操作单项目出库';
                        $stockJectArr[$key]['detailed_type'] = 1;
                        $stockJectArr[$key]['user_id'] = $formData['user_id'];
                        $stockJectArr[$key]['warehouse_id'] = $value['warehouse_id'];
                        $stockJectArr[$key]['createtime'] = time();
                        $stockJectArr[$key]['updatetime'] = time();
                        $stockJectArr[$key]['status'] = 1;
                        $stockJectArr[$key]['unit_price']    = $product_price / $product_info->specs * $value['product_num'];
                        $stockJectArr[$key]['begin_num']     = $begin_num;
                        $stockJectArr[$key]['end_num']       = $begin_num - $value['product_num'];
                    }
                    Db::name('stock')->insertAll($stockJectArr);
                }
                // halt($buyProducts);
                if(!empty($buyProducts)){
                    $deposit = [];
                    
                    foreach ($buyProducts as $key => $value) {
                        $begin_num = $StockModel->getBeginNum($value['warehouse_id'],$value['product_id']);
                        $product_price = $StockModel->getProductPrice($value['warehouse_id'],$value['product_id']); // 成本价
                        if($product_price == 0){
                            $product_info = ProductModel::get($value['product_id']);
                            $product_price = $product_info->price1;
                        }
                        if($value['is_deposit'] == 2){
                            
                            $deposit[] = [
                                'user_id' => $formData['user_id'],
                                'product_id' => $value['product_id'],
                                'num' => $value['num'],
                                'address' => '操作单产品寄存',
                                'status' => 1,
                                'createtime' => time(),
                                'updatetime' => time(),
                                'bak' => '操作单产品寄存',
                                'shop_id' => $formData['shop_id'],
                                'sn' => $formData['sn'],
                                'warehouse_id' => $value['warehouse_id'],
                                'price' => $value['price2'],
                                'unit_price' => $product_price * $value['num']
                            ];
                        }else{
                            
                            $stockDuctArr[$key]['sn'] = $formData['sn'];
                            $stockDuctArr[$key]['product_id'] = $value['product_id'];
                            $stockDuctArr[$key]['product_num'] = $value['num'];
                            $stockDuctArr[$key]['product_name'] = $value['name'];
                            $stockDuctArr[$key]['shop_id'] = $formData['shop_id'];
                            $stockDuctArr[$key]['type'] = '出库';
                            $stockDuctArr[$key]['bak'] = '操作单产品出库';
                            $stockDuctArr[$key]['detailed_type'] = 2;
                            $stockDuctArr[$key]['user_id'] = $formData['user_id'];
                            $stockDuctArr[$key]['warehouse_id'] = $value['warehouse_id'];
                            $stockDuctArr[$key]['createtime'] = time();
                            $stockDuctArr[$key]['status'] = 1;
                            $stockDuctArr[$key]['price'] = $value['price2'];
                            $stockDuctArr[$key]['unit_price'] = $product_price * $value['num'];
                            $stockDuctArr[$key]['begin_num']     = $begin_num;
                            $stockDuctArr[$key]['end_num']       = $begin_num - $value['num'];
                        }

                    }
                    // halt($deposit);
                    if(!empty($stockDuctArr)){
                         Db::name('stock')->insertAll($stockDuctArr);
                    }
                    if(!empty($deposit)){
                         $aa = Db::name('deposit')->insertAll($deposit);
                    }

                }

                // 项目现金支付
                if($price1 > 0){ // 现金支付
                    $sys_bal_log_ins = [
                         'sn' => $formData['sn'],
                         'type' => 1,  // 项目收入
                         'account_id' => $postData['account_id'],
                         'price' => $price1,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('system_balance_log')->insert($sys_bal_log_ins);
                }

                // 产品现金支付
                if($pricePro1 > 0){ // 现金支付
                    $sys_bal_log_ins = [
                         'sn' => $formData['sn'],
                         'type' => 2,  // 项目收入
                         'account_id' => $postData['account_id'],
                         'price' => $pricePro1,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('system_balance_log')->insert($sys_bal_log_ins);
                }
                 // 项目会员卡支付
                if($price2 > 0){
                    $user_bal_ject_log = [
                         'sn' => $formData['sn'],
                         'type' => 2,  // 项目收入
                         'price' => $price2,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('user_balance_log')->insert($user_bal_ject_log);
                }
                // 产品会员卡支付
                if($pricePro2 > 0){
                    $user_bal_duct_log = [
                         'sn' => $formData['sn'],
                         'type' => 3,  // 项目收入
                         'price' => $pricePro2,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('user_balance_log')->insert($user_bal_duct_log);
                }
                // 项目会员卡赠送支付
                if($price5 > 0){
                    $user_bal_ject_log = [
                         'sn' => $formData['sn'],
                         'type' => 2,  // 项目收入
                         'price' => $price5,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'is_give' => 2,
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('user_balance_log')->insert($user_bal_ject_log);
                }
                // 产品会员卡赠送支付
                if($pricePro5 > 0){
                    $user_bal_duct_log = [
                         'sn' => $formData['sn'],
                         'type' => 3,  // 项目收入
                         'price' => $pricePro5,
                         'createtime' => time(),
                         'updatetime' => time(),
                         'is_give' => 2,
                         'user_id' => $formData['user_id']
                     ];
                    Db::name('user_balance_log')->insert($user_bal_duct_log);
                }
                // 项目疗程卡结算
                if(!empty($card_ject)){
                    
                    
                    

                    foreach ($card_ject as $key => $value) {
                        // 生成使用记录
                        $start_num = UserCardLogModel::getUserCards($formData['user_id'], $key);
                        $price = ProjectModel::getProjectPrice($key);
                        $detailLog[] = [
                            'userid'    => $formData['user_id'],
                            'cid'       => $key,
                            'price'     => $price * array_sum($card_ject[$key]),
                            'start_num' => $start_num,
                            'use_num'   => array_sum($card_ject[$key]),
                            'end_num'   => $start_num - array_sum($card_ject[$key]),
                            'type'      => 2,   
                            'createtime'=> time()
                        ];

                        $card_ject_ids = Db::name('user_card_log')
                                        ->where('user_id',$formData['user_id'])
                                        ->where('pid',$key)
                                        ->where('use',1)
                                        ->where('type',1)
                                        ->limit(array_sum($card_ject[$key]))
                                        ->column('id');
                        Db::name('user_card_log')->where('id','in',$card_ject_ids)->update(['use'=>2,'use_sn'=>$formData['sn']]);
                    }
                    
                    UserCardDetailLogModel::insertAll($detailLog);
                }
                // 产品卡结算
                if(!empty($card_duct)){
                    foreach ($card_duct as $key => $value) {
                        $card_duct_ids = Db::name('user_card_log')->where('user_id',$formData['user_id'])->where('pid',$key)->where('use',1)->where('type',2)->limit(array_sum($card_duct[$key]))->column('id');
                        Db::name('user_card_log')->where('id','in',$card_duct_ids)->update(['use'=>2,'use_sn'=>$formData['sn']]);
                    }
                }
                $jixiao = [];
                foreach ($projects as $key => $value) {
                    if($value['settlement'] == 1){          // 现金支付
                        $account_type = '现金';
                    } else if ($value['settlement'] == 2) {  // 会员卡
                        $account_type = '会员卡';
                    } else if ($value['settlement'] == 3) {  // 赠送
                        $account_type = '赠送';
                    } else if ($value['settlement'] == 4) {  // 疗程卡
                        $account_type = '疗程卡';
                    } else if ($value['settlement'] == 10000) {  // 疗程卡
                        $account_type = '会员卡赠送余额';
                    }

                    // 绩效********************************************************
                    $meirongshi = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('id,nick');

                    // dump($value );
                    $jixiao[] = [
                        'admin_id' => $value['adviser_id'],
                        'user_id' => $formData['user_id'],
                        'project' => '项目购买--'.$value['project_name'],
                        'num' => $value['num'],
                        'price' => $value['price'],
                        'shougong' => 0,
                        'settlement' => $account_type,
                        'shop_id' => $formData['shop_id'],
                        'admin_type' => '顾问',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $formData['sn'],
                    ];
                    foreach ($meirongshi as $k => $v) {
                        $jixiao[] = [
                            'admin_id' => $k,
                            'user_id' => $formData['user_id'],
                            'project' => '项目购买--'.$value['project_name'],
                            'num' => $value['num'],
                            // 'price' => $value['price'],  //  客户要求修改金额
                            'price' => round(($value['price'] / count($meirongshi)),2),
                            'shougong' => round(($value['shougong'] / count($meirongshi)),2),
                            'settlement' => $account_type,
                            'shop_id' => $formData['shop_id'],
                            'admin_type' => '美容师',
                            'proportion' => 0,
                            'createtime' => date('Y-m-d H:i:s',time()),
                            'sn' => $formData['sn'],
                        ];
                    }

                }
                if(!empty($buyProducts)){
                    foreach ($buyProducts as $key => $value) {
                        if($value['settlement'] == 1){          // 现金支付
                            $account_type = '现金';
                        } else if ($value['settlement'] == 2) {  // 会员卡
                            $account_type = '会员卡';
                        } else if ($value['settlement'] == 3) {  // 赠送
                            $account_type = '赠送';
                        } else if ($value['settlement'] == 4) {  // 疗程卡
                            $account_type = '疗程卡';
                        } else if ($value['settlement'] == 10000) {  // 疗程卡
                            $account_type = '会员卡赠送余额';
                        }


                        // 绩效********************************************************
                        $meirongshi = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('id,nick');

                        // dump($value );
                        $jixiao[] = [
                            'admin_id' => $value['adviser_id'],
                            'user_id' => $formData['user_id'],
                            'project' => '产品购买--'.$value['name'],
                            'num' => $value['num'],
                            'price' => $value['price2'],
                            'shougong' => 0,
                            'settlement' => $account_type,
                            'shop_id' => $formData['shop_id'],
                            'admin_type' => '顾问',
                            'proportion' => 0,
                            'createtime' => date('Y-m-d H:i:s',time()),
                            'sn' => $formData['sn'],
                        ];
                        foreach ($meirongshi as $k => $v) {
                            $jixiao[] = [
                                'admin_id' => $k,
                                'user_id' => $formData['user_id'],
                                'project' => '产品购买--'.$value['name'],
                                'num' => $value['num'],
                                // 'price' => $value['price2'],
                                'price' => round(($value['price2'] / count($meirongshi)),2),
                                'shougong' => 0,
                                'settlement' => $account_type,
                                'shop_id' => $formData['shop_id'],
                                'admin_type' => '美容师',
                                'proportion' => 0,
                                'createtime' => date('Y-m-d H:i:s',time()),
                                'sn' => $formData['sn'],
                            ];
                        }


                    }

                }
                if(count($jixiao) > 0){
                    Db::name('achievements')->insertAll($jixiao);
                }
                    // 绩效********************************************************
                    Db::name('user')->where('id',$formData['user_id'])->update(['last_login_time'=>time()]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->axiosMsg($e->getMessage(),false);
            }
            return $this->axiosMsg('结算完成！',true);
        }




        // 用户购买的疗程卡
        $userCards = [];
        // $userCards = Db::name('user_card_log')->alias('ucl')->join('project p', 'p.id=ucl.pid')->field('ucl.pid,name,count(ucl.id) as num')->where('user_id',$formData['user_id'])->where('ucl.type',1)->group('pid')->where('use',1)->select();
        $userCards = Db::name('user_card_log')->alias('ucl')
        ->join('project p', 'p.id=ucl.pid')
        ->field('ucl.pid,name,count(ucl.id) as num')
        ->where('user_id',$formData['user_id'])
        ->where('ucl.type',1)
        ->where('use',1)
        ->group('pid')->select();
        $this->assign('userCards',$userCards);

        $cardList = Db::name('course')->where('status',1)->select();
        $this->assign('cardList', $cardList);
        $warehouses = Db::name('warehouse')->field('id,name')->where('shop_id',session('shop_id'))->where('type',0)->select();
        $this->assign('warehouses',$warehouses);

        return $this->fetch();
    }

    /**
     * [cwsh 财务审核]
     * @return [type] [description]
     */
    public function cwsh()
    {
        $where = [];
        // if ($this->hisiModel) {// 通过Model更新
        if($this->hisiModel){

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                $postData = $this->request->post();

                if ($model->save($postData, $where) === false) {
                    // return $this->error($model->getError());
                    return $this->axiosMsg($model->getError(),false);
                }
                return $this->axiosMsg('保存成功',true);
                // return $this->success('保存成功', '');
            }
            $formData = $model->where($where)->find();
        }

        $this->assign('formData', $formData);
        $this->assign('project_data', json_decode($formData->project_data,true));
        $this->assign('buy_product', json_decode($formData->buy_product,true));
        $this->assign('recharge', json_decode($formData->recharge,true));
        $this->assign('card_data', json_decode($formData->card_data,true));
        $warehouses = Db::name('warehouse')->where('shop_id',session('shop_id'))->field('id,name')->select();
        $this->assign('warehouses',$warehouses);
        if(!is_empty($this->request->param('xx')) && $this->request->param('xx') == 2){
            // $this->assign('formData', $formData);
            $this->view->engine->layout(false);
               return $this->fetch('dayin');
        }
        return $this->fetch();
    }


    public function lookOperation()
    {
        $id = $this->request->param('id');
        $where = [
            ['id','=',$id]
        ];
        $formData = Db::name('subscribe')->where($where)->find();
        if(!$formData){
            return $this->error('数据不存在或没有权限');
        }
        // halt(json_decode($formData['project_data']));
        $this->assign('formData', $formData);
        $this->assign('project_data', json_decode($formData['project_data'],true));
        $this->assign('buy_product', json_decode($formData['buy_product'],true));
        $this->assign('recharge', json_decode($formData['recharge'],true));
        $this->assign('card_data', json_decode($formData['card_data'],true));
        $warehouses = Db::name('warehouse')->where('shop_id',session('shop_id'))->field('id,name')->select();
        $this->assign('warehouses',$warehouses);
        return $this->fetch();
    }
}
